package com.jwiki.app.jkeeper.controller;

import java.io.File;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.jwiki.app.jkeeper.common.data.Response;
import com.jwiki.app.jkeeper.config.Configurations;
import com.jwiki.app.jkeeper.controller.form.PropertyForm;
import com.jwiki.app.jkeeper.service.PropertyService;

import net.coobird.thumbnailator.Thumbnails;

@RestController
@RequestMapping("/property")
public class PropertyController extends BaseController {

    @Autowired
    private PropertyService propertyService;

    @RequestMapping("/saveProperty")
    public Response saveProperty(MultipartFile file, PropertyForm form) throws Exception {
        Response response = getResponse();
        // save file
        if(file != null) {
            String baseUrl = Configurations.getResourceBase();
            String subFilePath = getContext().getUserName();
            File subUrlFile = new File(baseUrl, subFilePath);
            if (!subUrlFile.exists()) {
                subUrlFile.mkdirs();
            }
            String localFileName = UUID.randomUUID().toString() + "."
                    + FilenameUtils.getExtension(file.getOriginalFilename());
            form.setImageUrl(subFilePath + "/" + localFileName);
            File localFile = new File(baseUrl, FilenameUtils.concat(subFilePath, localFileName));
            file.transferTo(localFile);
            // resize file
            Thumbnails.of(localFile).size(480, 540).toFile(localFile);
            response.setSuccess(true);
        }
        // save property
        response.setSuccess(propertyService.saveProperty(form));
        return response;
    }

     @RequestMapping("/getProperty")
     public Response getProperty(@RequestBody PropertyForm form) {
         Response response = getResponse();
         response.setData(propertyService.getProperty(form));
         response.setSuccess(true);
         return response;
     }

     @RequestMapping("/getPropertyByPage")
     public Response getPropertyByPage(@RequestBody PropertyForm form) {
         Response response = getResponse();
         response.setData(propertyService.getPropertyByPage(form));
         response.setSuccess(true);
         return response;
     }

     @RequestMapping("/removeProperty")
     public Response removeProperty(@RequestBody List<Long> propertyIds) {
         Response response = getResponse();
         response.setSuccess(propertyService.removeProperty(propertyIds));
         return response;
     }

}
